#!/usr/bin/env bash
set -euf -o pipefail

# Validate required environment variables
: "${GITHUB_TOKEN:?GITHUB_TOKEN is required}"
: "${GITHUB_REPOSITORY:?GITHUB_REPOSITORY is required}"
: "${GITHUB_REPOSITORY_OWNER:?GITHUB_REPOSITORY_OWNER is required}"
: "${VERSION_TAG:?VERSION_TAG is required}"

# Get the previous tag
PREVIOUS_TAG="$(git ls-remote --tags origin | grep -oE '20[0-9]{6}-[0-9]{4}-[a-f0-9]{6,8}$' | sort | tail -n2 | head -n1)"

# Check if PREVIOUS_TAG is empty and exit with an error if so
if [[ -z "${PREVIOUS_TAG}" ]]; then
  echo "Error: No previous tag found. Exiting."
  exit 1
fi

# Echo PREVIOUS_TAG for debugging purposes
echo "Previous tag: ${PREVIOUS_TAG}"

# Define the GitHub API URL for the release
RELEASE_API_URL="https://api.github.com/repos/${GITHUB_REPOSITORY}/releases/tags/${VERSION_TAG}"

# Check if the release exists
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token ${GITHUB_TOKEN}" "${RELEASE_API_URL}")

if [[ "$HTTP_STATUS" -eq 404 ]]; then
  # Release not found, so create a new release
  echo "Creating new GitHub release..."
  if ! gh release create "${VERSION_TAG}" \
    --title "Release ${VERSION_TAG}" \
    --generate-notes \
    --repo "${GITHUB_REPOSITORY}"; then
    echo "Error: Failed to create release" >&2
    exit 1
  fi
fi
